package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.mapper.ProductMapper;
import com.example.demo.mapper.ProductStarMapper;
import com.example.demo.pojo.Product;
import com.example.demo.pojo.ProductStar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductStarService {

    @Autowired
    private ProductStarMapper productstarmapper;

    @Autowired
    private ProductMapper productMapper;

    public ProductStar findByProductIdAndUserId(Integer productId, Integer userId) {
        QueryWrapper<ProductStar> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId).eq("user_id", userId);
        return productstarmapper.selectOne(queryWrapper);
    }

    public void addStar(Integer productId, Integer userId) {
        productstarmapper.insert(new ProductStar(productId, userId, true));
        UpdateWrapper<Product> updateWrapper = new UpdateWrapper<>();
        productMapper.update(null, updateWrapper.setSql("like_number = like_number + 1"));
    }

    public void changeLikeState(Integer productId, Integer userId, boolean like_state) {
        UpdateWrapper<ProductStar> updateWrapper1 = new UpdateWrapper<>();
        UpdateWrapper<Product> updateWrapper2 = new UpdateWrapper<>();
        updateWrapper1.eq("product_id", productId).eq("user_id", userId);

        productstarmapper.update(new ProductStar(productId, userId, like_state), updateWrapper1);
        if (like_state) {
            productMapper.update(null, updateWrapper2.setSql("like_number = like_number + 1"));
        } else {
            productMapper.update(null, updateWrapper2.setSql("like_number = like_number - 1"));
        }
    }
}
